class Counter {
  constructor (limit) {
    this.limit = limit;
  }

  [Symbol.iterator] () {
    let count = 1,
        limit = this.limit;
    return {
      next () {
        if (count <= limit) {
          return { done: false, value: count++ };
        } else {
          return { done: true, value: undefined };
        }
      },

      return () {
        console.log('Exiting early');
        return { done: true };
      }
    };
  }
}

const counter1 = new Counter(5);
for (let i of counter1) {
  if (i > 2) break;
  console.log('counter1 关闭前：', i);
}
for (let i of counter1) {
  console.log('counter1 关闭后重新开始迭代：', i); // 重新开始迭代
}

const counter2 = new Counter(5);
const [a, b] = counter2;  // Exiting early

// 数组的迭代器不可关闭
const arr = [1, 2, 3, 4, 5];
const iter1 = arr[Symbol.iterator]();
for (let i of iter1) {
  console.log('arr 关闭前：', i); // 1 2 3
  if (i > 2) break;
}
for (let i of iter1) {
  console.log('arr 关闭后重新迭代：', i); // 4 5
}
for (let i of iter1) {
  // 不会打印，迭代器是按需创建的一次性对象
  console.log('重新开始迭代：', i);
}

const iter2 = arr[Symbol.iterator]();
iter2.return = function () {
  console.log('Exiting early');
  return { done: true };
}
for (let i of iter2) {
  console.log('iter2关闭前：', i); // 1 2 3 Exiting early
  if (i > 2) break;
}
for (let i of iter2) {
  console.log('iter2关闭后：', i); // 4 5
}